#![allow(dead_code)]
use lazy_static::*;

pub type Result<T> = std::result::Result<T, String>;

lazy_static! {
    pub static ref READ_OVER:Message = Message::new(0,Vec::new()).set_status(MessageStatus::Over);  //与客户断开连接
    pub static ref MSG_UNDEFINED:Message = Message::new(0,"未定义消息处理函数，请检查消息头是否正确".as_bytes().to_vec());
}

#[derive(Clone)]
pub enum MessageStatus {
    Over,
    Normal,
}

#[derive(Clone)]
pub struct Message {
    pub header: u16,
    pub body: Vec<u8>,
    pub status: MessageStatus,
    pub error: String,
}

unsafe impl Send for Message {}

impl Message {
    pub fn new_null() -> Self {
        Message {
            header: 0,
            body: Vec::new(),
            status: MessageStatus::Normal,
            error: String::new(),
        }
    }
    pub fn new(h: u16, b: Vec<u8>) -> Self {
        Message {
            header: h,
            body: b,
            status: MessageStatus::Normal,
            error: String::new(),
        }
    }
    pub fn set_header(&mut self, h: u16) {
        self.header = h;
    }
    pub fn set_body_from_vec(&mut self, b: Vec<u8>) {
        self.body = b;
    }
    pub fn set_status(mut self, status: MessageStatus) -> Self {
        self.status = status;
        self
    }
    pub fn set_error(mut self, err: String) -> Self {
        self.error = err;
        self
    }
    pub fn encode_to_slice(&mut self) -> Vec<u8> {
        let mut buf = self.header.to_le_bytes().to_vec();
        buf.append(&mut (self.body.len() as u16).to_le_bytes().to_vec());
        buf.append(&mut self.body);
        buf
    }
    pub fn encode_from_json<T: serde::Serialize>(&mut self, t: &T) -> Result<()> {
        match serde_json::to_vec(t) {
            Err(e) => Err(e.to_string()),
            Ok(o) => {
                self.body = o;
                Ok(())
            }
        }
    }
    pub fn decode_to_json<'a, T: serde::Deserialize<'a>>(&'a self) -> Result<T> {
        match serde_json::from_slice(self.body.as_slice()) {
            Err(e) => {
                log_debug_ln!("解码错误:{:?}", e);
                Err(e.to_string())
            }
            Ok(o) => Ok(o),
        }
    }
    pub fn decode_body_to_string(&self) -> String {
        format!("{}",String::from_utf8_lossy(self.body.as_slice()))
    }
    pub fn decode_body_to_u32(&self) -> u32 {
        u32::from_le_bytes([self.body[0],self.body[1],self.body[2],self.body[3]])
    }
}
